<template>
  <div v-if="editOpen">
    <p style="color:red">填写注意：项目立项通过后，项目绩效目标只能比申报时多，不能少!</p>
    <t-table :selected-row-keys="selectedRowKeys" @select-change="(val) => { selectedRowKeys = val }" rowKey="id" :data="data"
      :columns="columns">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #expectResultType="{ row }">
        <t-cascader clearable filterable @change="(val, content) => { onChange(val, content, row) }"
          :status="row.expectResultTypeStatus" :keys="{ value: 'id', label: 'name' }" v-model="row.expectResultType"
          :options="menuOptions">
          <div slot="tips" v-if="row.expectResultTypeStatus === 'error'">不能为空</div>
        </t-cascader>


      </template>
      <template #count="{ row }">
        <template v-if="row.quantization">
          <t-input-number v-if="row.quantization === '1'" :allowInputOverLimit="false" clearable v-model="row.count"
            :min="1" placeholder="请输入"></t-input-number>
          <t-textarea v-else @change="() => { if (row.note !== '') { row.noteStatus = 'default' } }" :status="row.noteStatus"
            clearable :autosize="{ minRows: 3 }" v-model="row.note" placeholder="请输入内容">
            <div slot="tips" v-if="row.noteStatus === 'error'">不能为空</div>
          </t-textarea>
        </template>

      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else>
    <t-table rowKey="id" :data="data" :columns="columns2">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #expectResultType="{ row, rowIndex }">
        <div
          :style="{ color: diffData.length >= rowIndex + 1 && diffData[rowIndex].expectResultType !== row.expectResultType ? 'red' : '' }">
          {{ row.expectResultType | filterParentsByTree(menuOptions, children = "children", id = "id", label = "name") }}
        </div>
      </template>

      <template #count="{ row, rowIndex }">
        <div v-if="row.quantization === '1'"
          :style="{ color: diffData.length >= rowIndex + 1 && diffData[rowIndex].count !== row.count ? 'red' : '' }"> {{
            row.expectResultType !== 99 ? row.count : '' }}</div>
        <span v-else :style="{ color: diffData.length >= rowIndex + 1 && diffData[rowIndex].note !== row.note ? 'red' : '' }"> {{
          row.note }}</span>
      </template>
    </t-table>
  </div>
</template>

<script>
export default {
  name: "item-approach-expectResults",
  dicts: ["expect_result_type"],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
    applyOpen: {
      type: Boolean,
      default: false
    },
    phaseType: {
      type: String,
      default: '1'
    },
    projectId: [String, Number],
    oldData: {
      type: Array,
      default: () => [],
    },
    useOldData: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      diffData: [],
      menuOptions: [],
      selectedRowKeys: [],
      dialogOpen: false,
      visible: true,
      formData: {
        sort: null,
        name: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: "不能为空",
          }
        ],
      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64,
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'expectResultType',
          title: "指标类别",
          align: "center",
          // ellipsis: true,
        },
        // {
        //   colKey: 'note',
        //   title: "成果说明",
        //   align: "center",
        // },
        {
          colKey: 'count',
          title: "指标值",
          align: "center",
        },
      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'expectResultType',
          title: "指标类别",
          align: "center",
          // ellipsis: true,
        },
        // {
        //   colKey: 'note',
        //   title: "成果说明",
        //   align: "center",
        // },
        {
          colKey: 'count',
          title: "指标值",
          align: "center",
          // ellipsis: true
        },
      ]
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val && val.length > 0 && this.useOldData) {
          let newArr = val.map(data => {
            return {
              ...data,
              initType: 'init'
            }
          })
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
        }
      }
    },
    data: {
      deep: true,
      immediate: true,
      handler (val) {
        const newData = this.data.map((val, index) => ({
          ...val,
          sort: index + 1,
          phaseType: this.phaseType,
          projectId: Number(this.projectId)
        }))
        this.$emit("input", newData);
      }
    },
    projectId: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val) {
          this.getData(val);
        }
      }
    },
    oldData: {
      deep: true,
      immediate: true,
      handler (val) {
        this.diffData = this.oldData;
      }
    },
  },
  async created () {
    // await this.getTreeSelect();
  },
  methods: {
    async getData () {
      await Promise.all([this.getTreeSelect()]);

      // 显示外层带的数据不查询
      if (this.useOldData) {
        return false;
      }
      this.$api.kjxm.project.projectExpectResultsGetByProjectIdAndPhaseType(Number(this.projectId), this.phaseType).then(res => {
        this.data = res.data;
        if (res.data.length <= 0 && this.phaseType !== '1' && this.editOpen === true) {
          let lastStep = Number(this.phaseType) - 1 > 0 ? Number(this.phaseType) - 1 : 1
          if (this.phaseType === '3') {
            lastStep = 1
          }
          this.$api.kjxm.project.projectExpectResultsGetByProjectIdAndPhaseType(Number(this.projectId), lastStep).then(res2 => {
            this.data = res2.data;
          }).catch((e) => {
            this.$message.error(e.toString());
          });
        }
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    /** 查询菜单下拉树结构 */
    getTreeSelect () {
      return this.$api.kjxm.kpi.list().then(response => {
        this.menuOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    checkData () {
      const isValidate = this.data.every((val, index) => {
        if (val.expectResultType === "") {
          this.$set(this.data[index], 'expectResultTypeStatus', 'error')
          this.$message.error(`项目绩效指标：第${index + 1}条指标类别不能为空`);
          return false;
        }
        this.$set(this.data[index], 'expectResultTypeStatus', 'default')
        if (val.quantization !== '1' && !val.note) {
          this.$set(this.data[index], 'noteStatus', 'error')
          this.$message.error(`项目绩效指标：第${index + 1}条指标值不能为空`);
          return false;
        }
        this.$set(this.data[index], 'noteStatus', 'default')
        return true;
      });
      return isValidate
    },
    addData () {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({
        id: newId,
        projectId: this.projectId,
        expectResultType: '',
        note: '',
        phaseType: this.phaseType,
        quantization: '',
        count: 1
      })
    },
    onChange (val, content, row) {
      if (row.expectResultType !== '') {
        row.expectResultTypeStatus = 'default'
      }
      row.quantization = content.node.data.quantization;
    },
    upData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray (arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style lang="less" scoped></style>
